package com.scsoft.dataacceptor.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.scsoft.dataacceptor.mongo.MongoResultData;
import com.scsoft.dataacceptor.util.TimeUtil;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class VocDbClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
	private static Logger log = LoggerFactory.getLogger("suma");
	private MongoResultData mongoResultData;

	public VocDbClientHandler(MongoResultData mongoResultData) {
		this.mongoResultData = mongoResultData;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf response) throws Exception {
		if (log.isInfoEnabled()) {
			log.info("client receive response data length:" + response.readableBytes());
		}
		byte[] rep = new byte[response.readableBytes()];
		response.readBytes(rep);
		String res = new String(rep, "UTF-8");
		if (log.isInfoEnabled()) {
			log.info(res);
		}
		if (null != res && res.indexOf("get_machlist1") > 0) {
			parseToList(res);
		}
		if (null != res && res.indexOf("refresh_mach_kind1") > 0) {
			saveNewMonitorData(res);
		}

	}

	private void saveNewMonitorData(String result) {
		try {
			String[] array = result.split("\\|");
			if (array.length >= 6 && "right".equals(array[3])) {
				String data = array[5];
				if (null != data && !"".equals(data)) {
					String[] datas = data.split("'");
					String num = datas[0];
					String kind = datas[1];
					String online = datas[2];
					String time = datas[3];
					Date date = TimeUtil.sdf1.parse(time);
					DBObject source = new BasicDBObject();

					source.put("SNCODE", num);
					source.put("MONITORCODE", "261");
					source.put("MONITORTIME", TimeUtil.sdf.format(date));
					source.put("DATASOURCES", "API");
					source.put("DATATYPE", "1min");
					source.put("CREATETIME", TimeUtil.getCurrentTime());
					BasicDBObject monitorData = new BasicDBObject();
					monitorData.put("machine_kind", kind);
					monitorData.put("machine_online", online);
					for (int i = 1; i <= 4; i++) {
						BasicDBObject road = new BasicDBObject();
						road.put("status", datas[4 + (i - 1)]);
						road.put("value", datas[8 + (i - 1)]);
						monitorData.put("road" + i, road);
					}
					source.put("MONITORDATA", monitorData);
					source.put("_id", num);
					mongoResultData.saveSrcData(source);
					source.put("_id", num + "#" + TimeUtil.sdf2.format(date));
					mongoResultData.saveSrcData(time.substring(0, 4), source);
					log.info("save success:{}", source.toString());
				}
			}
		} catch (Exception e) {
			log.warn("parse to NewMonitorData exception!", e);
		}

	}

	private List<String> parseToList(String result) {
		List<String> list = new ArrayList<String>();
		try {
			String[] array = result.split("\\|");
			if (array.length >= 6) {
				String[] fields = array[5].split("'");
				for (String field : fields) {
					log.info(field);
					list.add(field);
				}
			}
		} catch (Exception e) {
			log.warn("parse to user exception!", e);
		}
		return list;
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}
}